﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace Elvex
{
    public static class Tcp
    {
        /// <summary>
        /// 网络连接
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public static NetSession Connect(string host, ushort port)
        {
            IPHostEntry hostEntry = Dns.GetHostEntry(host);
            Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(hostEntry.AddressList, port);
            return socket.Connected ? NetManager.CreateSession(socket) : null;
        }

        public static IPAddress[] DNSAnalysis( string host ) 
        {
            return Dns.GetHostEntry(host).AddressList;
        }

        public static void Connect(string host, ushort port, Action<NetSession> callback)
        {
            Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            socket.BeginConnect(host, port, (res) => { AsyncConnectCallback(res, callback); }, socket);
        }

        public static void Connect(IPAddress address, ushort port, Action<NetSession> callback)
        {
            Socket socket = new Socket(new IPEndPoint(address, port).AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.BeginConnect(address, port, (res) => { AsyncConnectCallback(res, callback); }, socket);
        }

        public static void Connect(IPAddress[] addresses, ushort port, Action<NetSession> callback)
        {
            Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            socket.BeginConnect(addresses, port, (res) => { AsyncConnectCallback(res, callback); }, socket);
        }

        private static void AsyncConnectCallback(IAsyncResult ar, Action<NetSession> callback)
        {
            Socket scoket = (Socket)ar.AsyncState;
            try
            {
                scoket.EndConnect(ar);
            }
            catch (Exception e)
            {
                Debug.LogErrorFormat("Net Connect Exception msg:{0}", e.Message);
            }
            finally
            {
                callback(scoket.Connected ? NetManager.CreateSession(scoket) : null);
            }
        }
    }
}
